<template>
  <div class="editor">
    <div class="editor" ref="editor"></div>
  </div>
</template>

<script>
import E from 'wangeditor'
import config from '@/config'
import store from '@/store'

const TOKEN = 'Bearer ' + store.state.token
const baseUrl =
  process.env.NODE_ENV === 'production'
    ? config.baseUrl.pro
    : config.baseUrl.dev
export default {
  name: 'wangEditor',
  data() {
    return {
      editor: null,
      info_: null
    }
  },
  props: {
    initContent: {
      type: String,
      default: ''
    }
  },
  watch: {
    initContent(val) {
      this.editor.txt.html(val)
    }
  },
  mounted() {
    this.setEditor()
  },
  methods: {
    setEditor() {
      this.editor = new E(this.$refs.editor)
      this.editor.customConfig.uploadImgServer = '/content/upload' // 服务端地址
      this.editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024 // 图片大小限制为3M
      this.editor.customConfig.uploadImgMaxLength = 5 // 限制一次最多上传 5 张图片
      this.editor.customConfig.uploadImgTimeout = 3000 // 设置上传超时时间
      this.editor.customConfig.uploadFileName = 'file'
      this.editor.customConfig.zIndex = 100
      this.editor.customConfig.uploadImgHeaders = {
        Authorization: TOKEN
      }
      this.editor.customConfig.uploadImgHooks = {
        customInsert: function(insertImg, result, editor) {
          // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
          // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

          // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：

          var url = baseUrl + result.data
          insertImg(url)

          // result 必须是一个 JSON 格式字符串！！！否则报错
        }
      }

      this.editor.customConfig.onchange = html => {
        this.info_ = html
        this.$emit('changeContent', this.info_)
      }
      this.editor.create()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
